<template>
    <div>
        <!--查询条件-->
      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('ledger.RelocationType')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.ydlx" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of changesList" :value="item.id" :key="index">{{ item.name }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('ledger.TransactOutFactory')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.oldBelongCompanyId" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of factoryList" :value="item.id" :key="index">{{ item.name }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('ledger.TransactInFactory')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.newBelongCompanyId" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of factoryList" :value="item.id" :key="index">{{ item.name }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" @click="changeNum()"
                        v-if="checkBtnPermission.dmsMoveApplyGetDeviceMoveList">{{$t('common.Query')}}</Button>
                <Button class="reset-btn" @click="reset"
                        v-if="checkBtnPermission.dmsMoveApplyGetDeviceMoveList">{{ $t('common.reset') }}</Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
        <div class="list-layout mt16">
          <div class="btns clear">

        <span class="title">{{ $t('common.listInformation') }}</span>
            <Button @click="handleAdd" v-if="checkBtnPermission.dmsMoveApplyAdd">{{ $t('ledger.NewMotion') }}</Button>
            <Button @click="exportTemplateClick" v-if="checkBtnPermission.dmsMoveApplyExport">
              {{ $t('common.batchExport') }}
            </Button>
            <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏'):$t('隐藏操作栏') }}</Button>

          </div>
          <div class="tableContent">
            <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" row-key="id" :columns="columnsList" :data="dataSource" @on-selection-change="handleSelectionChange">
              <template slot-scope="{ row }" slot="action">
                <span class="operationBtn" v-has="'dmsMoveApplyGetDmsMoveApply'"
                      @click="handleDetail(row)">
                  <i class="iconfont zy-common-chakan"></i>
                  {{$t('common.Check')}}
                </span>
                <span class="operationBtn" v-show="row.moveStatus == 1 && checkBtnPermission.dmsMoveApplyDelete && row.applyStatus!=1"
                      @click="handleRevoke(row)">
                  <i class="iconfont zy-common-fanhui"></i>
                  {{$t('common.Withdraw')}}
                </span>
                <span class="operationBtn" v-show="row.moveStatus == 1 && checkBtnPermission.dmsMoveApplyDelete"
                      @click="handleDelete(row)">
                  <i class="iconfont zy-common-shanchu"></i>
                  {{$t('common.Delete')}}
                </span>
                <!-- <span class="operationBtn" v-show="row.applyStatus === 1 && checkBtnPermission.dmsMoveApplyUpdateApplyStatus" @click="handleSubmit(row)">提交审批</span> -->
                <!-- <span class="operationBtn" v-show="row.applyStatus === 0 && checkBtnPermission.dmsMoveApplyUpdateApplyStatus" @click="handleConfirm(row)">{{$t('maintenance.Confirmed')}}</span>
                <span class="operationBtn" v-show="row.applyStatus === 0 && checkBtnPermission.dmsMoveApplyUpdate" @click="handleEdit(row)">{{$t('common.Edit')}}</span> -->
              </template>
            </Table>
          </div>
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total" :selected="ids.length" />
            <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                  @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
          </div>
        </div>
        <Modal :mask-closable="false" v-model="delelteVisible" :title="$t('common.Delete')" class="modal-title-layout">
          <div class="icon red">
            <i class="iconfont zy-common-shanchu"></i>
          </div>
          <p class="title">
            <span>{{$t('common.sureDelete')}}</span>
          </p>
            <div slot="footer">
                <Button type="default" @click="delelteVisible = false">{{$t('common.Cancle')}}</Button>
                <Button type="primary" :loading="delLoading" @click="handleDeleteOk">{{$t('maintenance.Confirmed')}}</Button>
            </div>
        </Modal>

    <Modal :mask-closable="false" v-model="revokeVisible" title="撤销异动单" class="modal-content-layout">
      <Form label-position="top" class="search-form">
        <FormItem label="撤销原因备注：" required>
          <Input type="text" v-model="revokeRemark" :placeholder="`${$t('common.inputInfo')}`"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="revokeVisible = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="revokeLoading" @click="handleRevokeOk">{{ $t('maintenance.Confirmed') }}
        </Button>
      </div>
    </Modal>
    <!--新增异动-->
    <!--        <add-changes-modal ref="addChangesModal" :factoryList="factoryList" :orgList="orgList"-->
    <!--            @handleRefresh="handleRefresh" />-->
  </div>
</template>

<script>
// import AddChangesModal from './AddChangesModal'
import fileDownload from 'js-file-download';
import recursion from "@/util/recursion";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "applyList",
  mixins:[toggleTableOperation],
  // components: {
  //     AddChangesModal,
  // },
  props: {
    factoryList: {
      type: Array,
      default: () => []
    },
    orgList: {
      type: Array,
      default: () => []
    },
    applyDataSource: {
      type: Array,
      default: () => []
    },
    dataTotal: {
      type: Number,
      default: () => 10
    }
  },
  data() {
    return {
      ids: [],
      delId: '',
      revokeId: '',
      total: this.dataTotal,
      pageNum: 1,
      pageSize: 10,
      revokeVisible: false,
      delelteVisible: false,
      delLoading: false,
      revokeLoading: false,
      revokeRemark: "",
      searchParams: {},
      checkBtnPermission: {},
      pageSizeOption: [10, 20, 30],
      changesList: [
        {id: 0, name: '全部'},
        {id: 1, name: '转售'},
        {id: 2, name: '调拨'},
        {id: 3, name: '租用'},
        {id: 4, name: '借用'},
        {id: 7, name: '借用归还'},
        {id: 5, name: '仅记录'},
        {id: 6, name: '委外生产借用'}
      ],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: `${this.$t('ledger.RelocationStatus')}`,
          key: 'moveStatus',
          align: 'center',
          minWidth: 150,
          render: (h, params) => {
            return h('div', params.row.moveStatus == 1 ? '未异动' : params.row.moveStatus == 2 ? '已完成' : '')
          },
          resizable: true
        },
        {
          title: `${this.$t('ledger.ApplicationStatus')}`,
          key: 'applyStatus',
          align: 'center',
          minWidth: 150,
          render: (h, params) => {
            return h('div', params.row.applyStatus === 1 ? '已撤销' : '已提交')
          },
          resizable: true
        },
        {
          title: `${this.$t('ledger.RelocationType')}`,
          key: 'ydlx',
          align: 'center',
          minWidth: 140,
          render: (h, params) => {
            return h('div', params.row.ydlx == 1 ? '转售' : params.row.ydlx == 2 ? '调拨' : params.row.ydlx == 3 ? '租用' : params.row.ydlx == 4 ? '借用' : params.row.ydlx == 5 ? '仅记录' : params.row.ydlx == 6 ? '委外生产借用' : '借用归还')
          },
          resizable: true
        },
        // {
        //     title: '异动单号',
        //     key: 'applyNo',
        //     align: 'center',
        //     minWidth: 200,
        //     // render: (h, params) => {
        //     //     return h('a',
        //     //         {
        //     //             style: {
        //     //                 color: 'blue',
        //     //                 cursor: 'pointer'
        //     //             },
        //     //             on: {
        //     //                 click: () => {
        //     //                     this.handleledgerDetail(params.row.deviceMId, params.row.assetsNo)
        //     //                 }
        //     //             }
        //     //         }, params.row.deviceMId)
        //     // }
        // },
        // {
        //     title: 'OA签核单号',
        //     key: 'oaNo',
        //     align: 'center',
        //     minWidth: 120
        // },
        {
          title: `${this.$t('ledger.AppliedBy')}`,
          key: 'applyUserName',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${this.$t('equipmentscrapped.ApplyTime')}`,
          key: 'createTime',
          align: 'center',
          minWidth: 200,
          resizable: true
        },
        {
          title: `${this.$t('ledger.ApplicationReason')}`,
          key: 'applyRemark',
          align: 'center',
          minWidth: 160,
          resizable: true
        },
        {
          title: `${this.$t('ledger.TransactOutFactory')}`,
          key: 'oldBelongCompanyName',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
          title: `${this.$t('ledger.TransactInFactory')}`,
          key: 'newBelongCompanyName',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        // {
        //     title: '调出成本中心',
        //     key: 'moveOutCostCenterName',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '调入成本中心',
        //     key: 'moveInCostCenterName',
        //     align: 'center',
        //     minWidth: 120
        // },
        {
          title: `${this.$t('ledger.ApplyTransactionNum')}`,
          key: 'moveNum',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 300,
          align: "center",
          fixed: 'right',
        }
      ],
      dataSource: this.applyDataSource,
    }
  },
  created() {
    this.getTableColumnsWidth(this.columns)
    this.searchList()
  },
  watch: {
    applyDataSource(newValue) {
      this.dataSource = newValue
    },
    dataTotal(newValue) {
      this.total = newValue
    },
  },
  mounted() {
    let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
    for (let item of itemList) {
      if (item.code == "dmsMoveApplyGetDeviceMoveList") {
        this.checkBtnPermission.dmsMoveApplyGetDeviceMoveList = true
      }
      if (item.code == 'dmsMoveApplyAdd') {
        this.checkBtnPermission.dmsMoveApplyAdd = true
      }
      // if(item.code=='dmsMoveApplyUpdate') {
      //     this.checkBtnPermission.dmsMoveApplyUpdate = true
      // }
      if (item.code == 'dmsMoveApplyGetDmsMoveApply') {
        this.checkBtnPermission.dmsMoveApplyGetDmsMoveApply = true
      }
      if (item.code == 'dmsMoveApplyDelete') {
        this.checkBtnPermission.dmsMoveApplyDelete = true
      }
      if (item.code == 'dmsMoveApplyExport') {
        this.checkBtnPermission.dmsMoveApplyExport = true
      }
      // if(item.code=='dmsMoveApplyUpdateApplyStatus') {
      //     this.checkBtnPermission.dmsMoveApplyUpdateApplyStatus = true
      // }
    }
  },
  methods: {
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id.toString()
            }
          })
          this.factoryList = arr
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },

    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'id',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleSelectionChange(selectionData) {
      // console.log(selectionData)
      let arr = []
      selectionData.forEach(item => {
        arr.push(item.id)
      })
      this.ids = arr
    },
    handleRefresh() {
      this.searchList()
    },
    //申请异动
    handleAdd() {
      // console.log(123)
      // this.$refs.addChangesModal.show('add')
      ///devBasic/equipmentsChangesManagement/equipmentsChangesList/addAndDetail
      this.$router.push(({
        path: "/devBasic/equipmentsChangesManagement/addAndDetail",
        query: {
          handleType: "add"

        }
      }))
    },
    //删除
    handleDelete(row) {
      this.delelteVisible = true
      this.delId = row.id
    },
    //撤销
    handleRevoke(row) {
      this.revokeRemark = ""
      this.revokeVisible = true
      this.revokeId = row.id
    },
    handleEdit(row) {
      // this.$refs.addChangesModal.show('edit', row)
      this.$router.push(({
        path: "/devBasic/equipmentsChangesManagement/addAndDetail",
        query: {
          handleType: "edit",
          ...row
        }
      }))
    },
    //详情页
    handleDetail(row) {
      // this.$refs.addChangesModal.show('detail', row, true)
      this.$router.push(({
        path: "/devBasic/equipmentsChangesManagement/addAndDetail",
        query: {
          handleType: "detail",
          ...row,
          detail: true
        }
      }))
    },
    handleConfirm(row) {
      if (this.revokeRemark == "") {
        this.$Message.warning(({content: "请填写撤销原因备注", duration: 6, closable: true}));
        return
      }
      this.axios({
        method: 'post',
        url: '/dms/dmsMoveApply/updateApplyStatus',
        params: {
          id: row.id,
          fstatus: 1,
          backReason: this.revokeRemark
        }
      }).then(res => {
        
        if (res.code === 200) {
          this.$Message.success(({content: '确认成功！', duration: 3, closable: true}))
          this.searchList()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleSubmit(row) {
      this.axios({
        method: 'post',
        url: '/dms/dmsMoveApply/updateApplyStatus',
        params: {
          id: row.id,
          fstatus: 2
        }
      }).then(res => {
        
        if (res.code === 200) {
          this.$Message.success(({content: '审批提交成功！', duration: 3, closable: true}))
          this.searchList()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleDeleteOk() {
      this.delLoading = true
      this.axios({
        method: 'post',
        url: '/dms/dmsMoveApply/delete',
        params: {
          id: this.delId
        }
      }).then(res => {
        
        if (res.code === 200) {
          this.searchList()
          this.$Message.success('删除成功！')
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.delelteVisible = false
        this.delLoading = false
      })
    },
    //撤销原因
    handleRevokeOk() {
      this.revokeLoading = true
      this.axios({
        method: 'post',
        url: '/dms/dmsMoveApply/updateApplyStatus',
        params: {
          id: this.revokeId,
          fstatus: 1,
          backReason: this.revokeRemark
        }
      }).then(res => {
        
        if (res.code === 200) {
          this.searchList()
          this.$Message.success('撤销成功！')
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.revokeVisible = false
        this.revokeLoading = false
      })
    },
    //导出
    exportTemplateClick() {
      let params = {
        ids: this.ids.toString(),
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key])
        }
      }
      const filName = '我的申请'
      this.axios({
        method: 'get',
        url: '/dms/dmsMoveApply/exportApply',
        responseType: 'blob',
        params: params
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })

    },
    reset(){
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const {length, last = length - 1} = arr
          this.$set(params, key, arr[last])
        } else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }

      }
      this.axios({
        method: 'get',
        url: '/dms/dmsMoveApply/getDeviceMoveList',
        params: params
      }).then(res => {
        
        if (res.code === 200) {
          this.dataSource = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
